<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\common;

use app\common\exception\HttpResponseException;
use Webman\RateLimiter\Limiter;


abstract class Api
{

    protected $request;

    public function __construct()
    {
        $this->request = request();
    }

    protected function response($code, $msg = '', $data = '')
    {
        // 频率限制 todo 过高请求 自动加入黑名单
        Limiter::check($this->request->ip(), 10, 5, trans('please_do_not_request_frequently'));

        $result = [
            'code' => $code,
            'msg'  => $msg ?: ($code ? trans('operation_successful') : trans('operation_failed')),
            'data' => $data,
            'time' => time(),
        ];
        throw new HttpResponseException(200, $result);
    }

    protected function success($msg = '', $data = '')
    {
        $this->response(1, $msg, $data);
    }

    protected function error($msg = '', $data = '')
    {
        if (is_array($msg)) {
            $code = $msg['code'];
            $msg  = $msg['msg'];
        } else {
            $code = 0;
        }
        $this->response($code, $msg, $data);
    }

}
